/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { closeTag, setCurrentMenu } from "../../store/reducers/tab";
import { useLocation, useNavigate } from "react-router-dom";
import { Tag, Space, TagProps } from "antd";

import "./index.css";

// 定义标签项类型
interface TagItem {
  name: string;
  path: string;
  label: string;
} // 补充Menu组件类型定义（在组件顶部）

const CommonTag: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const navigate = useNavigate();

  // 获取 Redux 状态
  const tabList = useSelector((state: any) => state.tab.tabList);
  const currentMenu = useSelector((state: any) => state.tab.currentMenu);

  // 切换标签
  const changeTag = (tag: TagItem) => {
    dispatch(setCurrentMenu(tag));
    navigate(tag.path);
  };

  // 处理标签关闭
  const handleClose = (tag: TagItem, index: number) => {
    const length = tabList.length - 1;
    dispatch(closeTag(tag));

    // 导航逻辑
    if (tag.path !== location.pathname) return;

    if (length === index) {
      const prevTag = tabList[index - 1];
      if (prevTag) {
        dispatch(setCurrentMenu(prevTag));
        navigate(prevTag.path);
      }
    } else {
      const nextTag = tabList[index + 1];
      if (nextTag) {
        dispatch(setCurrentMenu(nextTag));
        navigate(nextTag.path);
      }
    }
  };

  // 渲染单个标签
  const renderTag = (isActive: boolean, item: TagItem, index: number) => {
    const tagProps: TagProps = {
      closable: isActive,
      onClose: () => handleClose(item, index),
      onClick: () => !isActive && changeTag(item),
      color: isActive ? "#55acee" : undefined,
      className: "custom-tag",
      style: { cursor: "pointer", marginBottom: 8 },
    };

    return (
      <Tag key={item.name} {...tagProps}>
        {item.label}
      </Tag>
    );
  };

  return (
    <Space size={[0, 8]} wrap className="common-tag">
      {tabList.map((item: TagItem, index: number) =>
        renderTag(item.path === currentMenu.path, item, index)
      )}
    </Space>
  );
};

export default CommonTag;
